package com.cooldatasoft.taskManager.user.gui;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import com.cooldatasoft.domain.model.Project;
import com.cooldatasoft.domain.model.Task;
import com.cooldatasoft.domain.model.User;
import com.cooldatasoft.domain.model.UserProjectRoles;
import com.cooldatasoft.domain.service.RolesService;
import com.cooldatasoft.domain.service.TaskService;
import com.cooldatasoft.domain.service.UserProjectRolesService;
import com.cooldatasoft.domain.service.UserService;
import com.cooldatasoft.security.TaskManagerSecurityManager;
import com.cooldatasoft.taskManager.component.TaskManagerNotification;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.event.Action;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
@Configurable(preConstruction=true)
public class UsersView extends CustomComponent implements Property.ValueChangeListener{
	@AutoGenerated
	private AbsoluteLayout mainLayout;
	@AutoGenerated
	private VerticalLayout verticalLayout_main;
	@AutoGenerated
	private Accordion accordion_projects;
	@AutoGenerated
	private NativeSelect nativeSelect_users;

	@Autowired
	private UserProjectRolesService userProjectRolesService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private TaskManagerSecurityManager taskManagersecurityManager;
	
	@Autowired
	private RolesService rolesService;
	
	private Project myCurrentProject;
	
	private static final Action ADD = new Action("write review");
	private static final Action EDIT = new Action("edit review");

	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public UsersView(Project currentProject) {
		myCurrentProject = currentProject;
		buildMainLayout();
		setCompositionRoot(mainLayout);
		if (myCurrentProject != null) {
			loadUsersToComboBox();
		}
	}
	
	private void loadUsersToComboBox(){
		nativeSelect_users.addListener(this);
		nativeSelect_users.setImmediate(true);
		nativeSelect_users.setNullSelectionAllowed(false);
		
		List<User> users = new ArrayList<User>();
		List<UserProjectRoles> projectsToUserWithRoleManager = new ArrayList<UserProjectRoles>();
		projectsToUserWithRoleManager = userProjectRolesService.getProjectsByUserWithRole(taskManagersecurityManager.getCurrentUser(), rolesService.getRoleById(1L));
		if(projectsToUserWithRoleManager != null){
			for (UserProjectRoles userProjectRole : projectsToUserWithRoleManager) {
				if (userProjectRole.getIdProject().getIdProject() == myCurrentProject.getIdProject()) {
					List<UserProjectRoles> programersOnProject = userProjectRolesService.getUsersByRoleOnProject(userProjectRole.getIdProject(), rolesService.getRoleById(2L));
					if(programersOnProject != null){
						for (UserProjectRoles userProjectRole1 : programersOnProject) {
							users.add(userProjectRole1.getIdUser());
						}
					}
				}
			}
			if(!users.isEmpty()){	
				for (User user : users) {
					nativeSelect_users.addItem(user);
				}
				nativeSelect_users.setValue(users.get(0));
			}else{
				nativeSelect_users.addItem("Any users");
				nativeSelect_users.setValue("Any users");
			}
		}else{
			nativeSelect_users.addItem("Any users");
			nativeSelect_users.setValue("Any users");
		}
	}
	
	private void createWriteTaskReviewModalWindow(String taskReview,final Task task,final Object item, final IndexedContainer tasksDoneContainer){
		
		final Window addTaskReviewWindowModal = new Window();

		addTaskReviewWindowModal.setWidth("400px");
		addTaskReviewWindowModal.setHeight("390px");
		addTaskReviewWindowModal.setModal(true);
		
		final TextArea taskReviewText = new TextArea(null,"");
		taskReviewText.setRows(20);
		taskReviewText.setColumns(30);
		taskReviewText.setImmediate(true);
		
		NativeButton createTaskReview = new NativeButton();
		createTaskReview.setStyleName("defaultBtn");
		
		if (taskReview == null){
			addTaskReviewWindowModal.setCaption("Write task review for task");
			createTaskReview.setCaption("Create task review");
		}else{
			addTaskReviewWindowModal.setCaption("Update task review for task");
			createTaskReview.setCaption("Update task review");
			taskReviewText.setValue(taskReview);
		}
		
		createTaskReview.addListener(new ClickListener() {
			
			@Override
			public void buttonClick(ClickEvent event) {
				String text = (String) taskReviewText.getValue();
				if(!text.equals("")){
					task.setTaskReview(text);
					task.setReviewer(taskManagersecurityManager.getCurrentUser().getName()+" "+taskManagersecurityManager.getCurrentUser().getSurname());
					taskService.updateTask(task);
								
					Embedded icon = new Embedded("",new ThemeResource("../centrumprosperitytheme/images/accept_icon1.png"));
					
					tasksDoneContainer.removeItem(item);

					Object itemId = tasksDoneContainer.addItem();					
					tasksDoneContainer.getItem(itemId).getItemProperty("reviewStatus").setValue(icon);
					tasksDoneContainer.getItem(itemId).getItemProperty("done").setValue(task);
					(addTaskReviewWindowModal.getParent()).removeWindow(addTaskReviewWindowModal);
				}else{
					getWindow().showNotification("you must write some text");
				}
			}
		});
		
		VerticalLayout vl = new VerticalLayout();
		vl.addComponent(taskReviewText);
		vl.addComponent(createTaskReview);
		
		addTaskReviewWindowModal.addComponent(vl);
		getWindow().addWindow(addTaskReviewWindowModal);
	}
	
	private void addProjectsToAccortion(){
		List<UserProjectRoles> userProjects = new ArrayList<UserProjectRoles>();
		List<UserProjectRoles> managerProjects = new ArrayList<UserProjectRoles>();
		
		try{
			User user = (User) nativeSelect_users.getValue();
			Object taskItemId = null;
			
			userProjects = userProjectRolesService.getProjectsByUserWithRole(user, rolesService.getRoleById(2L));
			managerProjects = userProjectRolesService.getProjectsByUserWithRole(taskManagersecurityManager.getCurrentUser(), rolesService.getRoleById(1L));
			
			if(userProjects != null && managerProjects != null){
				for (UserProjectRoles managerProject : managerProjects) {
					for (UserProjectRoles userProject : userProjects) {
						if(userProject.getIdProject().equals(managerProject.getIdProject())){
							HorizontalLayout hl = new HorizontalLayout();
							
							hl.setWidth("100%");
							hl.setHeight("100%");
							
							final Table tasksInProgressTable = new Table();
							tasksInProgressTable.setHeight("100%");
							tasksInProgressTable.setWidth("100%");
							
							tasksInProgressTable.addListener(new ItemClickListener() {
								
								@Override
								public void itemClick(ItemClickEvent event) {
									if(event.getButton() == ItemClickEvent.BUTTON_LEFT){
										Item item = tasksInProgressTable.getItem(event.getItemId());
										if (item != null) {
											Task task = (Task) item.getItemProperty("inProgress").getValue();
											if (task != null) {
												getWindow().showNotification(TaskManagerNotification.showTaskNotification("task info", task));
											}
										}		
									}
								}
							});
							
							IndexedContainer tasksInProgressContainer = new IndexedContainer();
							tasksInProgressContainer.addContainerProperty("inProgress", Task.class, null);		
							tasksInProgressTable.setContainerDataSource(tasksInProgressContainer);
							
							final Table tasksDoneTable = new Table();
							tasksDoneTable.setWidth("100%");
							tasksDoneTable.setHeight("100%");
							
							final IndexedContainer tasksDoneContainer = new IndexedContainer();
							tasksDoneContainer.addContainerProperty("done", Task.class, null);	
							tasksDoneContainer.addContainerProperty("reviewStatus", Embedded.class, null);	
							tasksDoneTable.setContainerDataSource(tasksDoneContainer);
							
							Project project = userProject.getIdProject();
							List<Task> tasksOnProject = taskService.getTasksOnProjectWithUser(user, project);
							if(tasksOnProject != null){
								for (Task task : tasksOnProject) {
									if(task.getTaskStatus().equalsIgnoreCase("in progress")){
										taskItemId = tasksInProgressTable.addItem();
										tasksInProgressContainer.getItem(taskItemId).getItemProperty("inProgress").setValue(task);
									}else if(task.getTaskStatus().equalsIgnoreCase("done")){
										taskItemId = tasksDoneContainer.addItem();
										tasksDoneContainer.getItem(taskItemId).getItemProperty("done").setValue(task);
										String taskReview = task.getTaskReview();
										if(taskReview != null){
											Embedded icon = new Embedded("",new ThemeResource("../centrumprosperitytheme/images/accept_icon1.png"));
											tasksDoneContainer.getItem(taskItemId).getItemProperty("reviewStatus").setValue(icon);
										}else{
											Embedded icon = new Embedded("",new ThemeResource("../centrumprosperitytheme/images/icon_deny.png"));
											tasksDoneContainer.getItem(taskItemId).getItemProperty("reviewStatus").setValue(icon);
										}
									}
								}
							}
							
							tasksDoneTable.addListener(new ItemClickListener() {
								
								@Override
								public void itemClick(ItemClickEvent event) {
									if(event.getButton() == ItemClickEvent.BUTTON_LEFT){
										Item item = tasksDoneTable.getItem(event.getItemId());
										if (item != null) {
											Task task = (Task) item.getItemProperty("done").getValue();
											if (task != null) {
												getWindow().showNotification(TaskManagerNotification.showTaskReviewNotification("task info", task));
											}
										}
									}
								}
							});
							
							tasksDoneTable.addActionHandler(new Action.Handler() {
								
								private static final long serialVersionUID = 1L;
								
								@Override
								public void handleAction(Action action, Object sender, final Object target) {
									if (action == ADD) {
										Task task = (Task) tasksDoneTable.getItem(target).getItemProperty("done").getValue();
										createWriteTaskReviewModalWindow(null, task,target,tasksDoneContainer);
									}else if (action == EDIT){
										Task task = (Task) tasksDoneTable.getItem(target).getItemProperty("done").getValue();
										createWriteTaskReviewModalWindow(task.getTaskReview(), task, target ,tasksDoneContainer);
									}
								}
								
								@Override
								public Action[] getActions(Object target, Object sender) {
									if (target == null) {
										return null;
									} else if (tasksDoneTable.getItem(target).getItemProperty("done").getValue() != null) {
										Task task = (Task) tasksDoneTable.getItem(target).getItemProperty("done").getValue();
										if(!task.getUser().equals(taskManagersecurityManager.getCurrentUser())){
											if (task.getTaskReview() == null) {
												return new Action[] { ADD };
											}else{
												return new Action[] { EDIT };
											}
										}else{
											return null;
										}
									}
									return null;
								}
							});
												
							hl.addComponent(tasksInProgressTable);
							hl.addComponent(tasksDoneTable);
							accordion_projects.addTab(hl,project.getName());
						}
					}
				}
			}
		}catch(ClassCastException ex){
			//nothing to do 
		}
	}

	@Override
	public void valueChange(ValueChangeEvent event) {
		accordion_projects.removeAllComponents();
		addProjectsToAccortion();
		
	}

	@AutoGenerated
	private AbsoluteLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new AbsoluteLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		mainLayout.setMargin(true);
		
		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");
		
		// verticalLayout_main
		verticalLayout_main = buildVerticalLayout_main();
		mainLayout.addComponent(verticalLayout_main, "top:0.0px;left:0.0px;");
		
		return mainLayout;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_main() {
		// common part: create layout
		verticalLayout_main = new VerticalLayout();
		verticalLayout_main.setImmediate(false);
		verticalLayout_main.setWidth("100.0%");
		verticalLayout_main.setHeight("100.0%");
		verticalLayout_main.setMargin(true);
		verticalLayout_main.setSpacing(true);
		
		// nativeSelect_users
		nativeSelect_users = new NativeSelect();
		nativeSelect_users.setCaption("Select your programmer");
		nativeSelect_users.setImmediate(false);
		nativeSelect_users.setWidth("200px");
		nativeSelect_users.setHeight("25px");
		verticalLayout_main.addComponent(nativeSelect_users);
		
		// accordion_projects
		accordion_projects = new Accordion();
		accordion_projects.setCaption("Programmers projects");
		accordion_projects.setImmediate(false);
		accordion_projects.setWidth("100.0%");
		accordion_projects.setHeight("100.0%");
		verticalLayout_main.addComponent(accordion_projects);
		verticalLayout_main.setExpandRatio(accordion_projects, 1.0f);
		
		return verticalLayout_main;
	}

}
